package net.takela.common.utils;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JSONUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);

    private static boolean prettyFormat = true;

    static {
        String env = System.getenv("json.pretty.format");
        if (env != null) {
            prettyFormat = BooleanUtils.toBoolean(env);
        }
    }
    /**
     * 
     */
    public static void configPrettyFormat(boolean prettyFormat) {
        JSONUtils.prettyFormat = prettyFormat;
    }
    /**
     * 
     */
    public static <T> T parse(String s, Type valueType) {
        T obj = null;

        try {
            obj = JSON.parseObject(s, valueType);
        } catch (Exception e) {
            LOGGER.error("parse fail {} {}", s, valueType, e);
        }
        return obj;
    }
    /**
     * 
     */
    public static Object parse(String s) {
        Object obj = null;
        String ARR_START_CHAR = "[";
        String MAP_START_CHAR = "{";
        if (s.startsWith(ARR_START_CHAR)) {
            obj = parse(s, ArrayList.class);
        } else if (s.startsWith(MAP_START_CHAR)) {
            obj = parse(s, HashMap.class);
        }

        return obj;
    }

    /**
     * 格式化字符串 字符串中使用{key}表示占位符
     *
     * @param str   需要匹配的字符串
     * @param param 参数集
     * @return
     */
    /**
     * 
     */
    public static String format(String str, Map<String, Object> param) {
        Pattern pattern = Pattern.compile("\\{(.*?)\\}");
        if (param == null) {
            return str;
        }
        try {
            Matcher matcher = pattern.matcher(str);
            while (matcher.find()) {
                String key = matcher.group();
                String keyClone = key.substring(1, key.length() - 1).trim();
                Object value = param.get(keyClone);
                if (value != null) {
                    str = str.replace(key, value.toString());
                }
            }
        } catch (Exception e) {
            LOGGER.error("format fail {} {}", str, param, e);
            return null;
        }
        return str;
    }
    /**
     * 
     */
    public static String toString(Object obj) {
        if (prettyFormat) {
            return JSON.toJSONString(obj, JSONWriter.Feature.PrettyFormat, JSONWriter.Feature.WriteMapNullValue);
        } else {
            return JSON.toJSONString(obj);
        }
    }
}
